<template>
  <div class="lawyer-case-library">
    <!-- 顶部操作栏 -->
    <header class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h1 class="page-title">案例库管理</h1>
          <p class="page-subtitle">管理和查看法律案例，为案件处理提供参考</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="showAddDialog = true">
            <i class="fas fa-plus mr-2"></i>添加案例
          </el-button>
          <el-button @click="refreshCases">
            <i class="fas fa-sync-alt mr-2"></i>刷新
          </el-button>
        </div>
      </div>
    </header>

    <!-- 搜索和筛选 -->
    <div class="filter-section">
      <div class="filter-content">
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索案例标题、关键词..."
            size="large"
            clearable
          >
            <template #prefix>
              <i class="fas fa-search"></i>
            </template>
          </el-input>
        </div>
        
        <div class="filter-controls">
          <el-select v-model="filters.category" placeholder="案例类型" clearable>
            <el-option label="交通事故" value="traffic"></el-option>
            <el-option label="医疗纠纷" value="medical"></el-option>
            <el-option label="劳动纠纷" value="labor"></el-option>
            <el-option label="合同纠纷" value="contract"></el-option>
            <el-option label="房产纠纷" value="property"></el-option>
            <el-option label="婚姻家庭" value="marriage"></el-option>
          </el-select>
          
          <el-select v-model="filters.difficulty" placeholder="难度等级" clearable>
            <el-option label="简单" value="easy"></el-option>
            <el-option label="中等" value="medium"></el-option>
            <el-option label="困难" value="hard"></el-option>
          </el-select>
          
          <el-select v-model="filters.result" placeholder="案例结果" clearable>
            <el-option label="胜诉" value="win"></el-option>
            <el-option label="败诉" value="lose"></el-option>
            <el-option label="和解" value="settlement"></el-option>
            <el-option label="调解" value="mediation"></el-option>
          </el-select>
          
          <el-button type="primary" @click="applyFilters">筛选</el-button>
          <el-button @click="clearFilters">重置</el-button>
        </div>
      </div>
    </div>

    <!-- 案例统计 -->
    <div class="stats-section">
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-icon bg-blue-100">
            <i class="fas fa-book text-blue-600"></i>
          </div>
          <div class="stat-content">
            <h3>{{ totalCases }}</h3>
            <p>总案例数</p>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon bg-green-100">
            <i class="fas fa-trophy text-green-600"></i>
          </div>
          <div class="stat-content">
            <h3>{{ winCases }}</h3>
            <p>胜诉案例</p>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon bg-yellow-100">
            <i class="fas fa-handshake text-yellow-600"></i>
          </div>
          <div class="stat-content">
            <h3>{{ settlementCases }}</h3>
            <p>和解案例</p>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon bg-purple-100">
            <i class="fas fa-star text-purple-600"></i>
          </div>
          <div class="stat-content">
            <h3>{{ avgRating.toFixed(1) }}</h3>
            <p>平均评分</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 案例列表 -->
    <div class="cases-section">
      <div class="cases-grid">
        <div
          v-for="caseItem in filteredCases"
          :key="caseItem.id"
          class="case-card"
          @click="viewCase(caseItem)"
        >
          <div class="case-header">
            <div class="case-category">
              <el-tag :type="getCategoryType(caseItem.category)">
                {{ getCategoryName(caseItem.category) }}
              </el-tag>
            </div>
            <div class="case-difficulty">
              <el-rate
                v-model="caseItem.difficulty"
                disabled
                show-text
                :max="3"
                :texts="['简单', '中等', '困难']"
              />
            </div>
          </div>
          
          <div class="case-content">
            <h3 class="case-title">{{ caseItem.title }}</h3>
            <p class="case-summary">{{ caseItem.summary }}</p>
            
            <div class="case-meta">
              <span class="meta-item">
                <i class="fas fa-calendar mr-1"></i>
                {{ formatDate(caseItem.date) }}
              </span>
              <span class="meta-item">
                <i class="fas fa-user mr-1"></i>
                {{ caseItem.lawyer }}
              </span>
              <span class="meta-item">
                <i class="fas fa-eye mr-1"></i>
                {{ caseItem.views }}次查看
              </span>
            </div>
            
            <div class="case-result">
              <el-tag :type="getResultType(caseItem.result)">
                {{ getResultText(caseItem.result) }}
              </el-tag>
              <span class="compensation">赔偿：￥{{ caseItem.compensation.toLocaleString() }}</span>
            </div>
          </div>
          
          <div class="case-actions">
            <el-button size="small" @click.stop="viewCase(caseItem)">查看详情</el-button>
            <el-button size="small" type="primary" @click.stop="editCase(caseItem)">编辑</el-button>
            <el-button size="small" type="danger" @click.stop="deleteCase(caseItem)">删除</el-button>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 48]"
          :total="filteredCases.length"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </div>

    <!-- 添加案例对话框 -->
    <el-dialog v-model="showAddDialog" title="添加案例" width="60%">
      <el-form :model="newCase" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="案例标题">
              <el-input v-model="newCase.title" placeholder="请输入案例标题"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="案例类型">
              <el-select v-model="newCase.category" placeholder="请选择类型" style="width: 100%">
                <el-option label="交通事故" value="traffic"></el-option>
                <el-option label="医疗纠纷" value="medical"></el-option>
                <el-option label="劳动纠纷" value="labor"></el-option>
                <el-option label="合同纠纷" value="contract"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="案例摘要">
          <el-input
            v-model="newCase.summary"
            type="textarea"
            :rows="3"
            placeholder="请输入案例摘要"
          ></el-input>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="承办律师">
              <el-input v-model="newCase.lawyer" placeholder="承办律师"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="案例结果">
              <el-select v-model="newCase.result" placeholder="请选择结果" style="width: 100%">
                <el-option label="胜诉" value="win"></el-option>
                <el-option label="败诉" value="lose"></el-option>
                <el-option label="和解" value="settlement"></el-option>
                <el-option label="调解" value="mediation"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="赔偿金额">
              <el-input v-model="newCase.compensation" type="number" placeholder="赔偿金额"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="addCase">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'LawyerCaseLibrary',
  setup() {
    const router = useRouter()
    
    // 响应式数据
    const searchKeyword = ref('')
    const currentPage = ref(1)
    const pageSize = ref(12)
    const showAddDialog = ref(false)
    
    const filters = reactive({
      category: '',
      difficulty: '',
      result: ''
    })
    
    const newCase = reactive({
      title: '',
      category: '',
      summary: '',
      lawyer: '',
      result: '',
      compensation: ''
    })
    
    // 模拟案例数据
    const cases = ref([
      {
        id: 1,
        title: '机动车追尾事故人身损害赔偿案',
        category: 'traffic',
        summary: '被告驾驶小客车追尾原告车辆，造成原告颈椎、腰椎损伤，经鉴定构成九级伤残。法院判决被告赔偿医疗费、误工费、伤残赔偿金等。',
        lawyer: '张律师',
        date: '2024-01-15',
        result: 'win',
        compensation: 280000,
        difficulty: 2,
        views: 156
      },
      {
        id: 2,
        title: '行人过马路交通事故死亡赔偿案',
        category: 'traffic',
        summary: '行人横穿马路时被机动车撞击致死，肇事司机承担主要责任。死者家属要求赔偿死亡赔偿金、丧葬费、精神损害抚慰金等。',
        lawyer: '李律师',
        date: '2024-01-10',
        result: 'win',
        compensation: 180000,
        difficulty: 3,
        views: 203
      },
      {
        id: 3,
        title: '电动车与机动车碰撞事故案',
        category: 'traffic',
        summary: '电动车闯红灯与正常行驶机动车发生碰撞，双方对责任认定存在争议。最终认定电动车承担主要责任，机动车承担次要责任。',
        lawyer: '王律师',
        date: '2024-01-08',
        result: 'settlement',
        compensation: 85000,
        difficulty: 1,
        views: 134
      },
      {
        id: 4,
        title: '酒驾交通肇事逃逸案',
        category: 'traffic',
        summary: '被告酒后驾驶撞伤行人后逃逸，构成交通肇事罪。在刑事附带民事诉讼中，被害人要求赔偿医疗费、误工费等损失。',
        lawyer: '赵律师',
        date: '2024-01-05',
        result: 'win',
        compensation: 450000,
        difficulty: 3,
        views: 189
      },
      {
        id: 5,
        title: '大货车侧翻压车事故案',
        category: 'traffic',
        summary: '大货车因超载侧翻压住小客车，造成车内人员死亡。家属要求货车司机及运输公司承担赔偿责任，涉及多项赔偿项目。',
        lawyer: '孙律师',
        date: '2024-01-03',
        result: 'win',
        compensation: 920000,
        difficulty: 3,
        views: 267
      },
      {
        id: 6,
        title: '停车场内车辆碰撞事故案',
        category: 'traffic',
        summary: '停车场内车辆倒车时碰撞，造成财产损失。双方对事故责任和赔偿金额存在争议，涉及停车场管理责任问题。',
        lawyer: '周律师',
        date: '2023-12-28',
        result: 'mediation',
        compensation: 35000,
        difficulty: 1,
        views: 145
      }
    ])
    
    // 计算属性
    const filteredCases = computed(() => {
      let result = cases.value
      
      if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase()
        result = result.filter(case_ =>
          case_.title.toLowerCase().includes(keyword) ||
          case_.summary.toLowerCase().includes(keyword)
        )
      }
      
      if (filters.category) {
        result = result.filter(case_ => case_.category === filters.category)
      }
      
      if (filters.difficulty) {
        const difficultyMap = { easy: 1, medium: 2, hard: 3 }
        result = result.filter(case_ => case_.difficulty === difficultyMap[filters.difficulty])
      }
      
      if (filters.result) {
        result = result.filter(case_ => case_.result === filters.result)
      }
      
      return result
    })
    
    const totalCases = computed(() => cases.value.length)
    const winCases = computed(() => cases.value.filter(c => c.result === 'win').length)
    const settlementCases = computed(() => cases.value.filter(c => c.result === 'settlement').length)
    const avgRating = computed(() => {
      const sum = cases.value.reduce((acc, c) => acc + c.difficulty, 0)
      return sum / cases.value.length || 0
    })
    
    // 方法
    const refreshCases = () => {
      // 重新生成一些随机数据来模拟刷新
      cases.value.forEach(c => {
        c.views = Math.floor(Math.random() * 300) + 50
      })
      ElMessage.success('案例列表已刷新')
    }
    
    const applyFilters = () => {
      currentPage.value = 1
    }
    
    const clearFilters = () => {
      Object.assign(filters, {
        category: '',
        difficulty: '',
        result: ''
      })
      searchKeyword.value = ''
      currentPage.value = 1
    }
    
    const viewCase = (caseItem) => {
      router.push(`/lawyer/case-library/${caseItem.id}`)
    }
    
    const editCase = (caseItem) => {
      router.push(`/lawyer/case-library/${caseItem.id}/edit`)
    }
    
    const deleteCase = async (caseItem) => {
      try {
        await ElMessageBox.confirm('确定要删除这个案例吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const index = cases.value.findIndex(c => c.id === caseItem.id)
        if (index > -1) {
          cases.value.splice(index, 1)
          ElMessage.success('案例删除成功')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('案例删除失败')
        }
      }
    }
    
    const addCase = () => {
      if (!newCase.title || !newCase.category) {
        ElMessage.error('请填写必填字段')
        return
      }
      
      const id = Math.max(...cases.value.map(c => c.id)) + 1
      cases.value.unshift({
        id,
        title: newCase.title,
        category: newCase.category,
        summary: newCase.summary,
        lawyer: newCase.lawyer,
        date: dayjs().format('YYYY-MM-DD'),
        result: newCase.result,
        compensation: parseInt(newCase.compensation) || 0,
        difficulty: 1,
        views: 0
      })
      
      showAddDialog.value = false
      Object.assign(newCase, {
        title: '',
        category: '',
        summary: '',
        lawyer: '',
        result: '',
        compensation: ''
      })
      
      ElMessage.success('案例添加成功')
    }
    
    const getCategoryType = (category) => {
      const typeMap = {
        traffic: 'danger',
        medical: 'warning',
        labor: 'success',
        contract: 'primary',
        property: 'info',
        marriage: ''
      }
      return typeMap[category] || ''
    }
    
    const getCategoryName = (category) => {
      const nameMap = {
        traffic: '交通事故',
        medical: '医疗纠纷',
        labor: '劳动纠纷',
        contract: '合同纠纷',
        property: '房产纠纷',
        marriage: '婚姻家庭'
      }
      return nameMap[category] || category
    }
    
    const getResultType = (result) => {
      const typeMap = {
        win: 'success',
        lose: 'danger',
        settlement: 'warning',
        mediation: 'info'
      }
      return typeMap[result] || ''
    }
    
    const getResultText = (result) => {
      const textMap = {
        win: '胜诉',
        lose: '败诉',
        settlement: '和解',
        mediation: '调解'
      }
      return textMap[result] || result
    }
    
    const formatDate = (date) => {
      return dayjs(date).format('YYYY-MM-DD')
    }
    
    return {
      searchKeyword,
      currentPage,
      pageSize,
      showAddDialog,
      filters,
      newCase,
      filteredCases,
      totalCases,
      winCases,
      settlementCases,
      avgRating,
      refreshCases,
      applyFilters,
      clearFilters,
      viewCase,
      editCase,
      deleteCase,
      addCase,
      getCategoryType,
      getCategoryName,
      getResultType,
      getResultText,
      formatDate
    }
  }
}
</script>

<style scoped>
.lawyer-case-library {
  padding: 24px;
  background-color: #f9fafb;
  min-height: 100vh;
}

/* 页面头部 */
.page-header {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 28px;
  font-weight: bold;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.page-subtitle {
  color: #6b7280;
  margin: 0;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 筛选区域 */
.filter-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.filter-content {
  display: flex;
  gap: 16px;
  align-items: center;
}

.search-box {
  flex: 1;
  max-width: 400px;
}

.filter-controls {
  display: flex;
  gap: 12px;
  align-items: center;
}

/* 统计区域 */
.stats-section {
  margin-bottom: 24px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-icon i {
  font-size: 24px;
}

.stat-content h3 {
  font-size: 24px;
  font-weight: bold;
  margin: 0 0 4px 0;
  color: #1f2937;
}

.stat-content p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

/* 案例列表 */
.cases-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.cases-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.case-card {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s ease;
  cursor: pointer;
  background: #fafafa;
}

.case-card:hover {
  border-color: #3b82f6;
  box-shadow: 0 4px 16px rgba(59, 130, 246, 0.1);
  transform: translateY(-2px);
}

.case-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.case-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 12px 0;
  line-height: 1.4;
}

.case-summary {
  color: #6b7280;
  font-size: 14px;
  line-height: 1.5;
  margin: 0 0 16px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.case-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.meta-item {
  font-size: 12px;
  color: #6b7280;
  display: flex;
  align-items: center;
}

.case-result {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.compensation {
  font-weight: 600;
  color: #059669;
  font-size: 14px;
}

.case-actions {
  display: flex;
  gap: 8px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  padding-top: 24px;
  border-top: 1px solid #e5e7eb;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .cases-grid {
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  }
  
  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .filter-content {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-controls {
    justify-content: center;
    flex-wrap: wrap;
  }
}

@media (max-width: 768px) {
  .lawyer-case-library {
    padding: 16px;
  }
  
  .cases-grid {
    grid-template-columns: 1fr;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .case-actions {
    justify-content: center;
  }
}
</style> 